import * as mongoose from 'mongoose';

import fastFormatTimeSchema from './base';
import paginate from './plugins/paginate';
import autoPopulateSubs from './plugins/auto-populate-subs';

const { Schema } = mongoose;

const dictionarySchema = new Schema(
  {
    name: Schema.Types.String,
    value: Schema.Types.String,
    locale: {
      type: Schema.Types.ObjectId,
      required: false
    },
    type: {
      type: Schema.Types.ObjectId,
      ref: 'dictionary-type',
    },
    creator: {
      type: Schema.Types.ObjectId,
      ref: 'user',
    },
    ...fastFormatTimeSchema(),
  },
  {
    versionKey: false,
    timestamps: true,
    toJSON: {
      getters: true,
      transform(doc, ret) {
        ret.id = ret._id;
        delete ret._id;
      },
    },
    toObject: {
      getters: true,
      transform(doc, ret) {
        ret.id = ret._id;
        delete ret._id;
      },
    },
  },
);

export default paginate(
  autoPopulateSubs({
    schema: dictionarySchema,
    methods: ['find', 'findOne'],
    populates: [
      {
        path: 'type',
        select: 'id code name',
      },
      {
        path: 'creator',
        select: 'id username nickName',
      },
    ],
  }),
);
